package Reports;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class DBConnecter {
	protected static Connection connection = null;

	protected static boolean debug = true;

	/**
	 * Get db connection
	 * 
	 * @param s1 -
	 *            driverClass
	 * @param s2 -
	 *            connectionString
	 * @param s3 -
	 *            userName
	 * @param s4 -
	 *            passwd
	 * @return database's connection
	 * 
	 * For example: JdbcDriverClass=oracle.jdbc.driver.OracleDriver
	 * ConnectionString=jdbc:oracle:thin:@142.100.15.151:1521:tceng DbUser=erp
	 * DbPass=erp
	 * @throws SQLException -
	 *             sql error
	 */
	public static Connection getConnection(
			String driverClass,
			String connectionString,
			String userName,
			String passwd) 
	throws SQLException {
		if (connection != null && connection.isClosed()) {
			connection = null;
		}

		if (connection == null) {
			if (debug) {
				System.err.println("Connecting " + userName + " to '"
						+ connectionString + "' with driver " + driverClass
						+ " ...");
			}
			// check driver
			try {
				Class.forName(driverClass);
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
			connection = DriverManager.getConnection(connectionString,
					userName, passwd);
		}
		return connection;

	}

	public static void closeConnection() throws SQLException {
		if (connection != null && !connection.isClosed()) {
			connection.commit();
			connection.close();
			if (debug) {
				System.err.println("Success to close Connecting");
			}
		}
		connection = null;
	}

	public static void beginTrans() throws SQLException {
		if (connection != null) {
			connection.setAutoCommit(false);
		}
	}

	/**
	 * commit a connection
	 * 
	 * @param conn
	 *            connection object to be committed
	 */
	public static void commit(Connection conn) throws SQLException {
		if (connection != null) {
			connection.commit();
			connection.setAutoCommit(true);
		}
	}

	/**
	 * rollback a connection
	 * 
	 * @param conn
	 *            connection object to be rollback
	 */
	public static void rollback() throws SQLException {
		if (connection != null) {
			connection.rollback();
		}
	}

	/**
	 * close һ����¼��
	 * 
	 * @param rs
	 *            ResultSet object to be closed
	 */
	public static void close(ResultSet rs) {
		try {
			if (rs != null) {
				rs.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * close a statements
	 * 
	 * @param stmt
	 *            statement object to be closed
	 */
	public static void close(Statement stmt) {
		try {
			if (stmt != null) {
				stmt.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}
